package edu.nf.project.services.employeeAndCustomerInformation.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import edu.nf.project.entitys.dto.employeeAndCustomerInformation.CouponDTO;
import edu.nf.project.entitys.entity.employeeAndCustomerInformation.convention.Coupon;
import edu.nf.project.entitys.entity.employeeAndCustomerInformation.relevancy.CustomerInfo_Coupon;
import edu.nf.project.entitys.entity.employeeAndCustomerInformation.relevancy.Member_Coupon;
import edu.nf.project.services.exception.derivedAnomalies.CouponException;
import edu.nf.project.mappers.employeeAndCustomerInformation.convention.CouponMapper;
import edu.nf.project.mappers.employeeAndCustomerInformation.relevancy.CustomerInfo_CouponMapper;
import edu.nf.project.mappers.employeeAndCustomerInformation.relevancy.Member_CouponMapper;
import edu.nf.project.services.employeeAndCustomerInformation.CouponService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.time.ZoneId;
import java.util.Date;
import java.util.List;
import java.util.stream.Stream;

/**
 * 优惠券服务实现类
 */
@Service
public class CouponServiceImpl implements CouponService {
    @Autowired
    private CouponMapper couponMapper;

    @Autowired
    private CustomerInfo_CouponMapper customerInfoCouponMapper;

    @Autowired
    private Member_CouponMapper memberCouponMapper;

    @Override
    public Page<Coupon> getCouponList(Page<Coupon> page) {
        return couponMapper.selectPage(page, null);
    }

    @Override
    public Coupon getCouponInfo(Integer couponId) {
        return couponMapper.selectById(couponId);
    }

    @Override
    @Transactional
    public boolean createCoupon(Coupon coupon) {
        return couponMapper.insert(coupon) > 0;
    }

    @Override
    @Transactional
    public boolean assignCouponToCustomer(Integer customerId, Integer couponId) {
        // 检查优惠券是否存在
        Coupon coupon = couponMapper.selectById(couponId);
        if (coupon == null) {
            throw new CouponException(40001, "优惠券不存在");
        }
        // 创建关联记录
        CustomerInfo_Coupon customerInfoCoupon = new CustomerInfo_Coupon();
        customerInfoCoupon.setCustomerId(customerId);
        customerInfoCoupon.setCouponId(couponId);
        // 设置获取时间（当前时间）
        LocalDateTime now = LocalDateTime.now();
        customerInfoCoupon.setObtainTime(LocalDateTime.from(now.atZone(ZoneId.systemDefault()).toInstant()));
        // 计算截止时间（获取时间 + 优惠券使用期限）
        LocalDateTime deadlineTime = now.plusDays(coupon.getTerm());
        customerInfoCoupon.setDeadlineTime(LocalDateTime.from(deadlineTime.atZone(ZoneId.systemDefault()).toInstant()));
        // 插入记录
        return customerInfoCouponMapper.insert(customerInfoCoupon) > 0;
    }

    @Override
    @Transactional
    public boolean assignCouponToMember(Integer memberId, Integer couponId) {
        // 检查优惠券是否存在
        Coupon coupon = couponMapper.selectById(couponId);
        if (coupon == null) {
            throw new CouponException(40001, "优惠券不存在");
        }
        // 创建关联记录
        Member_Coupon memberCoupon = new Member_Coupon();
        memberCoupon.setMemberId(memberId);
        memberCoupon.setCouponId(couponId);
        // 插入记录
        return memberCouponMapper.insert(memberCoupon) > 0;
    }

    @Override
    public List<CouponDTO> listCouponByUsersId(Integer uId) {
        List<CouponDTO> coupons = couponMapper.listCouponByUsersId(uId);
        //根据Stream流过滤出优惠券的过期时间大于今天的
        List<CouponDTO> list = coupons.stream().
                filter(coupon -> coupon.getDeadlineTime().compareTo(new Date()) > 0).toList();
        // 直接返回过滤后的列表，如果没有有效优惠券则返回空列表
        return list;
    }

    @Override
    public List<Coupon> listCouponInfo() {
        LambdaQueryWrapper<Coupon> queryWrapper = new LambdaQueryWrapper<>();
        return couponMapper.selectList(queryWrapper);
    }

    /**
     * 修改
     * @param customer_id 顾客ID
     * @param coupon_id 优惠卷ID
     * @param deadline_time 期限
     * @return
     */
    @Override
    public Boolean addCouponCustomer(Integer customer_id, Integer coupon_id, Long deadline_time) {
        CustomerInfo_Coupon coupon = new CustomerInfo_Coupon();
        coupon.setCustomerId(customer_id);
        coupon.setCouponId(coupon_id);
        coupon.setObtainTime(LocalDateTime.now());
        coupon.setDeadlineTime(LocalDateTime.now().plusDays(deadline_time));

        return customerInfoCouponMapper.insert(coupon)>0;
    }

    @Override
    @Transactional
    public boolean updCoupon(Coupon coupon) {
        // 检查优惠券是否存在
        if (coupon.getCouponId() == null) {
            throw new CouponException(40001, "优惠券ID不能为空");
        }
        
        Coupon existingCoupon = couponMapper.selectById(coupon.getCouponId());
        if (existingCoupon == null) {
            throw new CouponException(40001, "优惠券不存在");
        }
        
        // 更新优惠券信息
        return couponMapper.updateById(coupon) > 0;
    }
}